﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Web.Security;
using System.Diagnostics.Contracts;

public partial class account_MyPurchases : System.Web.UI.Page
{
    private List<SalesRecord> uncompletedRecords;
    private List<SalesRecord> completedRecords;
        
    protected void Page_Load(object sender, EventArgs e)
    {
        string userId = Membership.GetUser().ProviderUserKey.ToString();

        getUncompletedRecord();
        getCompletedRecord();


        //getCompletedPurchasesSource(userId);
    }


    class SalesRecord
    {
        public int Id { get; set; }

        public DateTime PlaceDate { get; set; }

        public DateTime CompletedDate { get; set; }

        public string Prograss { get; set; }

        public string UserId { get; set; }

        public List<SalesItem> SalesItems { get; set; }

        public SalesRecord()
        {
            SalesItems = new List<SalesItem>();
        }
    }

    class SalesItem
    {
        public int Product { get; set; }

        public int Quantity { get; set; }

        public int Rating { get; set; }

        public string CoverPhoto { get; set; }
        public string ProductName { get; set; }

    }


    protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "delete")
        {

            var salesRecordID = e.CommandArgument;

            //修改当前此记录的Prograss为canceled
            var connString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ASPNETDBConnectionString"];
            if (connString == null)
                throw new ArgumentNullException("无法获取指定的数据库连接字符串。");
            using (SqlConnection connection = new SqlConnection(connString.ConnectionString))
            {
                connection.Open();
                string userId = Membership.GetUser().ProviderUserKey.ToString();

                SqlCommand command = new SqlCommand(
                    string.Format("update [sale record] set Prograss='canceled' where [Id]='{0}'", salesRecordID),
                    connection);
                command.CommandType = System.Data.CommandType.Text;
                int affectedRows = command.ExecuteNonQuery();
                Contract.Assert(affectedRows > 0, "数据库操作失败，该记录没有从数据库表中删除。请稍候再试。");
            }
        }

        Response.Write("<script language=javascript>alert(Cancel the purchase successfully! )</script>");
        Response.Write(e.CommandArgument);
    }
    protected void Repeater2_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "confirm")
        {
            var salesRecordID = e.CommandArgument;

            //修改当前此记录的Prograss为canceled
            var connString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ASPNETDBConnectionString"];
            if (connString == null)
                throw new ArgumentNullException("无法获取指定的数据库连接字符串。");
            using (SqlConnection connection = new SqlConnection(connString.ConnectionString))
            {
                connection.Open();
                string userId = Membership.GetUser().ProviderUserKey.ToString();

                SqlCommand command = new SqlCommand(
                    string.Format("update [sale record] set Prograss='confirmed' where [Id]='{0}'", salesRecordID),
                    connection);
                command.CommandType = System.Data.CommandType.Text;
                int affectedRows = command.ExecuteNonQuery();
                Contract.Assert(affectedRows > 0, "数据库操作失败，该记录没有从数据库表中删除。请稍候再试。");
            }
        }
        Response.Write("<script language=javascript>alert(Confirm the purchase successfully)</script>");
        Response.Write(e.CommandArgument);
    } 
    protected void uncompletedSalesRecordSource_Selecting(object sender, LinqDataSourceSelectEventArgs e)
    {
        e.Result = uncompletedRecords;
    }
    protected void arrivedAndCompletedSource_Selecting(object sender, LinqDataSourceSelectEventArgs e)
    {
        
        e.Result = completedRecords;
    }

    private void getCompletedRecord()
    {
        var connString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ASPNETDBConnectionString"];
        if (connString == null)
            throw new ArgumentNullException("无法获取指定的数据库连接字符串。");

        using (SqlConnection connection = new SqlConnection(connString.ConnectionString))
        {
            connection.Open();

            string userId = Membership.GetUser().ProviderUserKey.ToString();
            SqlCommand command = new SqlCommand(
                string.Format(@"
    SELECT   id, placedDate, completedDate, Prograss, UserId
    FROM      [Sale Record]
    WHERE   (UserId = '{0}') AND (Prograss = 'confirmed') OR
                    (Prograss = 'sent') OR
                    (Prograss = 'arrived')",
 userId), connection);

            command.CommandType = System.Data.CommandType.Text;
            var completedSaleRecordReader = command.ExecuteReader();


            completedRecords = new List<SalesRecord>();
            while (completedSaleRecordReader.Read())
            {
                completedRecords.Add(new SalesRecord
                {
                    Id = completedSaleRecordReader.GetInt32(0),
                    PlaceDate = completedSaleRecordReader.GetDateTime(1),
                    //因为是uncompleted 交易记录，所以不用 CompletedDate = saleRecordReader.GetDateTime(2),
                    Prograss = completedSaleRecordReader.GetString(3),
                    UserId = completedSaleRecordReader.GetGuid(4).ToString()
                });
            }

        }

        using (SqlConnection connection = new SqlConnection(connString.ConnectionString))
        {


            for (int i = 0; i < completedRecords.Count; i++)
            {
                connection.Open();
                var salesItemReader = new SqlCommand(
                    string.Format(@"
    SELECT   SalesItem.salesRecord, SalesItem.product, SalesItem.quantity, SalesItem.rating, Product.*
    FROM      SalesItem INNER JOIN
                    Product ON SalesItem.product = Product.id
    WHERE   (salesRecord = {0})",
     completedRecords[i].Id),
     connection) { CommandType = System.Data.CommandType.Text }.ExecuteReader();

                while (salesItemReader.Read())
                {
                    completedRecords[i].SalesItems.Add(new SalesItem
                    {
                        Product = salesItemReader.GetInt32(1),
                        Quantity = salesItemReader.GetInt16(2),
                        //Rating = salesItemReader.GetByte(3),
                        CoverPhoto = salesItemReader.IsDBNull(11) ? "12" : salesItemReader.GetString(11),
                        ProductName = salesItemReader.GetString(5)

                    });
                }

                connection.Close();
            }


        }
    }
    private void getUncompletedRecord()
    {
        var connString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ASPNETDBConnectionString"];
        if (connString == null)
            throw new ArgumentNullException("无法获取指定的数据库连接字符串。");


        using (SqlConnection connection = new SqlConnection(connString.ConnectionString))
        {
            connection.Open();

            string userId = Membership.GetUser().ProviderUserKey.ToString();
            SqlCommand command = new SqlCommand(
                string.Format(@"
SELECT   id, placedDate, completedDate, Prograss, UserId
FROM      [Sale Record]
WHERE   (UserId = '{0}') AND (Prograss = 'not accepted') OR
                (Prograss = 'accepted  ') OR
                (Prograss = 'canceled')",
 userId), connection);

            command.CommandType = System.Data.CommandType.Text;
            var saleRecordReader = command.ExecuteReader();

            uncompletedRecords = new List<SalesRecord>();
            while (saleRecordReader.Read())
            {
                uncompletedRecords.Add(new SalesRecord
                {
                    Id = saleRecordReader.GetInt32(0),
                    PlaceDate = saleRecordReader.GetDateTime(1),
                    //因为是uncompleted 交易记录，所以不用 CompletedDate = saleRecordReader.GetDateTime(2),
                    Prograss = saleRecordReader.GetString(3),
                    UserId = saleRecordReader.GetGuid(4).ToString()
                });
            }
        }

        using (SqlConnection connection = new SqlConnection(connString.ConnectionString))
        {


            for (int i = 0; i < uncompletedRecords.Count; i++)
            {
                connection.Open();
                var salesItemReader = new SqlCommand(
                    string.Format(@"
SELECT   SalesItem.salesRecord, SalesItem.product, SalesItem.quantity, SalesItem.rating, Product.*
FROM      SalesItem INNER JOIN
                Product ON SalesItem.product = Product.id
WHERE   (salesRecord = {0})",
     uncompletedRecords[i].Id),
     connection) { CommandType = System.Data.CommandType.Text }.ExecuteReader();

                while (salesItemReader.Read())
                {
                    uncompletedRecords[i].SalesItems.Add(new SalesItem
                    {
                        Product = salesItemReader.GetInt32(1),
                        Quantity = salesItemReader.GetInt16(2),
                        //Rating = salesItemReader.GetByte(3),
                        CoverPhoto = salesItemReader.IsDBNull(11) ? "12" : salesItemReader.GetString(11),
                        ProductName = salesItemReader.GetString(5)

                    });
                }

                connection.Close();
            }


        }
    }
}
